package cn.sunzq.springdata.elasticsearch.demo.config;

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient;
import org.springframework.data.elasticsearch.client.reactive.ReactiveRestClients;
import org.springframework.data.elasticsearch.config.AbstractReactiveElasticsearchConfiguration;

/**
 * @创建人 孙中泉
 * @创建时间 2021/7/26
 * @描述
 */
//@Configuration
//@EnableReactiveElasticsearchRepositories(basePackages  = "cn.sunzq.springdata.elasticsearch.demo.repositories")
public class ReactiveElasticsearchRepositoriesConfig extends AbstractReactiveElasticsearchConfiguration {

    @Value("${es.connect-timeout:-1}")
    private int connectTimeout;

    @Value("${es.socket-timeout:-1}")
    private int socketTimeout;

    @Value("${es.connection-request-timeout:-1}")
    private int connectionRequestTimeout;

    @Value("${es.username:es_user}")
    private String userName;

    @Value("${es.password:FXP7YnnKrZoprqET}")
    private String password;

    @Value("${es.hosts:10.122.149.201}")
    private String hosts;

    @Value("${es.port:9200}")
    private int port;

    @Value("${es.max-retry-timeout-millis:300000}")
    private int maxRetryTimeoutMillis;

    @Override
    public ReactiveElasticsearchClient reactiveElasticsearchClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

        ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo(hosts).withBasicAuth(userName, password)
                .withConnectTimeout(connectTimeout).withSocketTimeout(socketTimeout).withHttpClientConfigurer(new RestClientBuilder.HttpClientConfigCallback(){

                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                        httpAsyncClientBuilder.disableAuthCaching();
                        return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                })
                .build();
        return ReactiveRestClients.create(clientConfiguration);
    }
}